<script setup lang="ts">
import { ref, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'

const router = useRouter()
const auth = useAuthStore()

const identifier = ref('')
const password = ref('')
const rememberMe = ref(true)

const canSubmit = computed(() => identifier.value.trim().length >= 3 && password.value.length >= 6)

async function onSubmit() {
  if (!canSubmit.value) return
  const ok = await auth.login({ identifier: identifier.value.trim(), password: password.value, rememberMe: rememberMe.value })

  if (ok) {
    // 确保用户状态完整后再跳转
    const isStateComplete = await auth.ensureUserState()
    if (isStateComplete) {
      router.push('/home')
    } else {
      auth.error = '登录成功但获取用户信息失败，请重试'
    }
  }
}
</script>

<template>
  <div class="auth-wrap">
    <div class="card">
      <div class="brand">라이브팬</div>

      <div class="form">
        <label>로그인 ID 또는 이메일</label>
        <input v-model="identifier" placeholder="login_id 또는 email" />

        <label>비밀번호</label>
        <input v-model="password" type="password" placeholder="비밀번호" />

        <div class="row">
          <label class="chk">
            <input type="checkbox" v-model="rememberMe" />
            로그인 상태 유지
          </label>
        </div>

        <button class="btn primary" :disabled="!canSubmit || auth.loading" @click="onSubmit">
          {{ auth.loading ? '로그인 중...' : '로그인' }}
        </button>
        <router-link class="btn ghost" to="/register">회원가입</router-link>

        <p v-if="auth.error" class="error">{{ auth.error }}</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.auth-wrap{min-height:100vh;display:flex;align-items:center;justify-content:center;background:linear-gradient(180deg,#f8fafc,#eef2ff)}
.card{width:420px;max-width:92vw;background:#fff;border-radius:16px;box-shadow:0 10px 30px rgba(0,0,0,.08);padding:32px}
.brand{font-weight:800;font-size:22px;letter-spacing:4px;color:#6366f1;text-align:center;margin-bottom:18px}
.form{display:flex;flex-direction:column;gap:10px}
label{font-size:13px;color:#374151}
input{height:42px;border:1px solid #e5e7eb;border-radius:10px;padding:0 12px;outline:none;transition:.2s}
input:focus{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,.15)}
.row{display:flex;align-items:center;justify-content:space-between}
.chk{display:flex;gap:8px;align-items:center;color:#6b7280;font-size:13px}
.btn{height:44px;border-radius:10px;border:none;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;margin-top:8px;text-decoration:none}
.btn.primary{background:#6366f1;color:#fff}
.btn.primary:disabled{opacity:.6;cursor:not-allowed}
.btn.ghost{border:1px solid #e5e7eb;color:#111827;background:#fff;margin-left:8px}
.error{color:#ef476f;margin-top:6px}
</style>

